package com.jzsm.modules.sender.senderService.impl.weixin;

import com.alibaba.fastjson.JSON;
import com.jzsm.modules.sender.bo.message.MessageBo;
import com.jzsm.modules.sender.enums.ChannelTypeEnum;
import com.jzsm.common.annotation.Channel;
import com.jzsm.common.utils.AssertUtils;
import com.jzsm.modules.sender.pojo.PushChannelAccount;
import com.jzsm.modules.sender.enums.DomainNameEnum;
import com.jzsm.modules.sender.senderService.AbstractMessageSender;
import com.jzsm.modules.sender.senderService.impl.weixin.utils.WorkWeixinUtils;
import lombok.AccessLevel;
import lombok.experimental.FieldDefaults;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * 企业微信应用 渠道
 */
@Channel(ChannelTypeEnum.WorkWeixinApp)
@Component
@FieldDefaults(level = AccessLevel.PRIVATE)
public class WorkWeixinAppMessageSender extends AbstractMessageSender {
    static final String PREFIX_URL = DomainNameEnum.WorkWeixinApp.getUrl() + "/cgi-bin/message";

    @Override
    public String sendMessage(String message, PushChannelAccount account) {
        final String url = PREFIX_URL + "/send";
        return run(url, message, account);
    }

    @Override
    public String sendMessage(MessageBo messageBo) {
        final String url = PREFIX_URL + "/send";
        return run(url, messageBo.getMessage(), messageBo.getAccount());
    }


    /**
     * 更新消息 根据 response_code
     *
     * @param message
     * @param account
     * @return
     */
    @Override
    public String updateMessage(String message, PushChannelAccount account) {
        final String url = PREFIX_URL + "/update_template_card";
        return run(url, message, account);
    }

    @Override
    public String recallMessage(String msgId, PushChannelAccount account) {
        String url = PREFIX_URL + "/recall";
        AssertUtils.isNotBlank("消息ID 不允许为空！", msgId);
        return run(url, msgId, account);
    }

    private String run(String url, String message, PushChannelAccount account) {
        String response = null;
        try {
            WxCpServiceImpl service = WorkWeixinUtils.getWxCpService(account);
            WxCpConfigStorage storage = service.getWxCpConfigStorage();

            HashMap map = JSON.parseObject(message, HashMap.class);
            // 注入应用ID
            map.put("agentid", storage.getAgentId());
            response = service.post(url, JSON.toJSONString(map));
        } catch (WxErrorException e) {
            AssertUtils.throwError(e.getMessage());
        }
        return response;
    }
}
